<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 解析配置
 * @param string $value 配置值
 * @return array|string
 */
if (!function_exists('parse_attr')) {
    function parse_attr ($value = '')
    {
        $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
        if (strpos($value, ':')) {
            $value = array();
            foreach ($array as $val) {
                list($k, $v) = explode(':', $val);
                $value[$k]   = $v;
            }
        } else {
            $value = $array;
        }

        return $value;
    }
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pk 主键名称
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @param integer $root
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 根据ID和PID返回一个树形结构
 * @param array $list 要转换的数据集
 * @param string $pk 主键名称
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @param integer $root
 * @return array
 */
function list_to_tree_two($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] = & $list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId =  $data[$pid];
			if ($root == $parentId) {
				$tree[$data['id']] = & $list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent                      = & $refer[$parentId];
					$parent[$child][$data['id']] = & $list[$key];
				}
			}
		}
	}
	return $tree;
}

/**
 * 对象转换成数组
 * @param object $object 数据对象
 * @return array
 */
function object_to_array(&$object)
{
    $object = json_decode( json_encode($object), true );

    return $object ? $object : null;
}

/**
 * 获取客户端IP地址
 * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param bool $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = null;
    if ($ip !== null) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }

            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 对用户的密码进行加密
 * @param $password
 * @param $encrypt // 传入加密串，在修改密码时做认证
 * @return array/password
 */
function encrypt_password($password, $encrypt = '')
{
    $pwd = array();
    $pwd['encrypt']  = $encrypt ? $encrypt : gen_random_string();
    $pwd['password'] = md5(trim($password) . md5($pwd['encrypt']));
    return $encrypt ? $pwd['password'] : $pwd;
}

/**
 * 产生一个指定长度的随机字符串,并返回给用户
 * @param type $len 产生字符串的长度
 * @return string 随机字符串
 */
function gen_random_string($len = 6)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9",
    );
    $charsLen = count($chars) - 1;
    // 将数组打乱
    shuffle($chars);
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

if (!function_exists('get_thumb')) {
    /**
     * 获取图片缩略图路径
     * @param int $id 附件id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_thumb($id = 0)
    {
        $path = model('admin/attachment')->getThumbPath($id);
        if (!$path) {
            return '/static/images/nopic.png';
        }
        return $path;
    }
}

if (!function_exists('get_file_name')) {
    /**
     * 根据附件id获取文件名
     * @param string $id 附件id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_file_name($id = '')
    {
        $name = model('admin/attachment')->getFileName($id);
        if (!$name) {
            return '没有找到文件';
        }
        return $name;
    }
}

if (!function_exists('get_file_path'))
{
    /**
     * 获取附件路径
     * @param int $id 附件id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_file_path($id = 0)
    {
        $path = model('admin/attachment')->getFilePath($id);
        if (!$path) {
            return '/static/images/nopic.png';
        }
        return $path;
    }
}

if (!function_exists('get_model_title')) {
    /**
     * 获取内容模型标题
     * @param string $id 内容模型标题
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_model_title($id = '')
    {
        $model_list = model('admin/data_model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['title'] : '';
    }
}

if (!function_exists('get_model_table')) {
    /**
     * 获取内容模型附加表名
     * @param int $id 模型id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_model_table($id = 0)
    {
        $model_list = model('admin/data_model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['table'] : '';
    }
}

if (!function_exists('get_model_type')) {
    /**
     * 获取内容模型类别：0-系统，1-普通，2-独立
     * @param int $id 模型id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_model_type($id = 0)
    {
        $model_list = model('admin/data_model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['type'] : '';
    }
}

if (!function_exists('format_bytes')) {
    /**
     * 格式化字节大小
     * @param  number $size      字节数
     * @param  string $delimiter 数字和单位分隔符
     * @return string            格式化后的带单位的大小
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function format_bytes($size, $delimiter = '') {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }
}

/**
 * 通用广告解析
 * @param integer $type 类型
 * @param string $json json串
 * @return string
 */
function format_advert_html($type, $json)
{
    $advertHtml = '';
    $data       = json_decode($json, true);
    switch ($type) {
        case 0: // 代码
            $advertHtml = $data['code'];
            break;
        case 1: // 文字
            $advertHtml = '<a href="'.$data['link'].'" target="_blank" style="';
            if ($data['color'] != '') {
                $advertHtml .= 'color:'.$data['color'];
            }
            $advertHtml .= '">'.$data['ad_text'].'</a>';
            break;
        case 2: // 图片
            $advertHtml = '<a href="'.$data['link'].'" target="_blank"><img src="'.get_file_path($data['one_pic']).'" style="';
            if ($data['width'] != '') {
                $advertHtml .= 'width:'.$data['width'].'px;';
            }
            if ($data['height'] != '') {
                $advertHtml .= 'height:'.$data['height'].'px;';
            }
            if ($data['alt'] != '') {
                $advertHtml .= '" alt="'.$data['alt'];
            }
            $advertHtml .= '" /></a>';
            break;
        case 3: // flash
            $advertHtml = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"';
            if ($data['width'] != '') {
                $advertHtml .= ' width="'.$data['width'].'"';
            }
            if ($data['height'] != '') {
                $advertHtml .= ' height="'.$data['height'].'"';
            }
            $advertHtml .= '><param name="quality" value="high" /><param name="movie" value="'.$data['link'].'" /><embed allowfullscreen="true"';
            if ($data['height'] != '') {
                $advertHtml .= ' height="'.$data['height'].'"';
            }
            $advertHtml .= ' pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'.$data['link'].'" type="application/x-shockwave-flash"';
            if ($data['width'] != '') {
                $advertHtml .= ' width="'.$data['width'].'"';
            }
            $advertHtml .= '></embed></object>';
            break;
    }

    return $advertHtml;
}

/**
 * 返回模型名称
 * @param integer $id
 */
function get_model_name($id = '')
{
    $model_list = model('admin/data_model')->getList();
    return isset($model_list[$id]) ? $model_list[$id]['title'] : '';
}